#include "../include/tinyxml2.h"
#include <iostream>

using namespace tinyxml2;

using std::cout;
using std::endl;
using std::string;
using std::cerr;

int main(){
    XMLDocument doc;

    string filename = "../corpus/webpages/auto.xml";
    
    // 1. 加载文件并检查错误
    if (doc.LoadFile(filename.c_str()) != XML_SUCCESS) {
        cout << "Error loading XML file: " << filename << endl;
        return -1;
    }

    // 2. 定位到 <channel> 节点
    XMLElement* rssNode = doc.RootElement(); // <rss> 节点
    if (!rssNode || strcmp(rssNode->Name(), "rss") != 0) {
        cout << "Error: Root <rss> element not found." << endl;
        return -1;
    }
    
    XMLElement* channelNode = rssNode->FirstChildElement("channel"); // <channel> 节点
    if (!channelNode) {
        cout << "Error: <channel> element not found." << endl;
        return -1;
    }

    // 3. 开始遍历第一个 <item> 节点
    // 从 <channel> 的第一个 <item> 子节点开始
    XMLElement *itemNode = channelNode->FirstChildElement("item");
    int item_count = 0;

    while (itemNode)
    {
        item_count++;
        cout << "------------------------------------------" << endl;
        cout << "📰 第 " << item_count << " 条新闻:" << endl;

        // 4. 提取 <item> 内的具体字段

        // 提取 <title>
        XMLElement *titleNode = itemNode->FirstChildElement("title");
        const char *titleText = titleNode ? titleNode->GetText() : "N/A";
        cout << "标题: " << titleText << endl;

        // 提取 <link>
        XMLElement *linkNode = itemNode->FirstChildElement("link");
        const char *linkText = linkNode ? linkNode->GetText() : "N/A";
        cout << "链接: " << linkText << endl;

        // 提取 <pubDate>
        XMLElement *pubDateNode = itemNode->FirstChildElement("pubDate");
        const char *pubDateText = pubDateNode ? pubDateNode->GetText() : "N/A";
        cout << "发布日期: " << pubDateText << endl;

        // 注意：<description> 的内容是 CDATA 包裹的 HTML 片段，
        // 提取方法一样，但后续处理可能需要去除 HTML 标签。
        XMLElement *descNode = itemNode->FirstChildElement("description");
        const char *descText = descNode ? descNode->GetText() : "N/A";
        cout << "描述: " << descText << endl; // 打印描述

        // 提取 <content>
        XMLElement *contNode = itemNode->FirstChildElement("content");
        const char *contText = contNode ? contNode->GetText() : "N/A";
        cout << "内容: " << contText << endl; // 打印内容

        // 指向下一个item节点
        itemNode = itemNode->NextSiblingElement("item");
    }

    cout << "------------------------------------------" << endl;
    cout << "✅ 共解析完成 " << item_count << " 条新闻项。" << endl;

    return 0;
}
